package hotLeetcode;

import java.util.HashSet;
import java.util.Set;

public class H141Leetcode {
    public boolean hasCycle(ListNode head) {
        ListNode fast = head;
        ListNode slow = head;

        while (fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if (fast == slow) return true;



        }

        return false;

    }

    // 用hash 法
    public boolean hasCycle2(ListNode head) {
        Set<ListNode> hashSet = new HashSet<>();
        while (head != null) {
            if (!hashSet.contains(head)) {
                hashSet.add(head);


            }else {
                return true;
            }
            head = head.next;

        }

        return false;
    }




      class ListNode {
       int val;
       ListNode next;
       ListNode(int x) {
           val = x;
           next = null;
       }
   }
}
